package com.shiwaixiangcun.customer.module.heath

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.fragment.LazyFragment
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView
import kotlinx.android.synthetic.main.layout_fragment_moment.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author   Administrator
 * Date     2018/1/22
 * Desc     健康动态
 */

class FragmentMoment : LazyFragment() {

    private var emptyView: View? = null
    private var tvEmpty: TextView? = null
    private var ivEmpty: ImageView? = null
    private var strToken: String? = null
    private var userID: Long? = null
    private var refreshToken: String? = null

    private var mList: ArrayList<HealthDynamicData>? = null
    private var mAdapter: AdapterHealthDynamic? = null

    var pageStart: Int = 1
    var pageSize: Int = 20

    override fun getContentViewLayoutID(): Int {
        return R.layout.layout_fragment_moment
    }

    override fun initViewsAndEvents(view: View) {
        strToken = AppSharePreferenceMgr.get(activity, ConfigSps.CURRENT_TOKEN, "") as String
        refreshToken = AppSharePreferenceMgr.get(activity, ConfigSps.CURRENT_REFRESH_TOKEN, "") as String
        pageSize = GlobalConfig.first_page
        pageSize = GlobalConfig.page_size
        emptyView = LayoutInflater.from(activity).inflate(R.layout.layout_common_empty, null, false)

        tvEmpty = emptyView?.findViewById(R.id.tv_empty)
        ivEmpty = emptyView?.findViewById(R.id.iv_empty)
        ivEmpty?.setImageResource(R.drawable.empty_health_moment)
        tvEmpty?.text = "您还没有健康动态~"
        mList = ArrayList()
        mAdapter = AdapterHealthDynamic(mList)
        rv_health_moment.layoutManager = LinearLayoutManager(activity)
        rv_health_moment.adapter = mAdapter


        mAdapter?.setLoadMoreView(CustomLoadMoreView())
        mAdapter?.setOnLoadMoreListener({
            pageStart += 1
            userID?.let { initData(it, true) }
        }, rv_health_moment)


    }

    private fun initData(id: Long, isLoadMore: Boolean) {
        OkGo.get<String>(GlobalApi.userHealthDynamic)
                .params("access_token", strToken)
                .params("customerId", id)
                .params("page.pn", pageStart)
                .params("page.size", pageSize)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        mAdapter?.loadMoreEnd(false)
                        mAdapter?.setEnableLoadMore(true)
                    }

                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonEntity<HealthDynamic>>() {}.type
                        val commonListEntity = JsonUtil.fromJson<CommonEntity<HealthDynamic>>(response?.body(), type)
                        when (commonListEntity.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                val size = commonListEntity.data.elements.size
                                if (isLoadMore) {
                                    if (size > 0) {

                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HEALTH_DYNAMIC, REQUEST_DATA, commonListEntity.data))
                                    }
                                    if (size == 0 || size < pageSize) {
                                        mAdapter?.loadMoreEnd(false)
                                    } else {
                                        mAdapter?.loadMoreComplete()
                                    }
                                } else {
                                    mAdapter?.setEnableLoadMore(true)
                                    if (size == 0) {
                                        mList?.clear()
                                        mAdapter?.emptyView = emptyView
                                        mAdapter?.notifyDataSetChanged()
                                    } else {
                                        mList?.clear()
                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HEALTH_DYNAMIC, REQUEST_DATA, commonListEntity.data))

                                    }
                                }
                            }
                            ResponseConfig.TOKEN_INVALID -> {
                                showToast("当前登录失效")
                                RefreshTokenUtil.refreshToken(mContext, refreshToken)
                            }
                        }
                    }

                })
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        when (simpleEvent.mEventType) {
            SimpleEvent.HEALTH_DYNAMIC -> {
                when (simpleEvent.mEventValue) {
                //获取数据更新界面
                    REQUEST_DATA -> {
                        val data = simpleEvent.data as HealthDynamic
                        if (data.elements.isEmpty()) {
                            mList?.clear()
                            mAdapter?.emptyView = emptyView
                            mAdapter?.notifyDataSetChanged()
                        } else {
                            mList?.clear()
                            mList?.addAll(data.elements)
                            mAdapter?.notifyDataSetChanged()
                        }
//                        loadDataToUi(data)
                    }

                }
            }
            SimpleEvent.HEALTH_CHANGE_FAMILY -> {
                when (simpleEvent.mEventValue) {
                    CHANGE_TAB -> {
                        val id = simpleEvent.data as Long
                        userID = id
                        if (this.isUserVisiable) {
                            Log.e(BUG_TAG, "change")
                            pageStart = GlobalConfig.first_page
                            initData(userID!!, false)
                        }
                    }
                }
            }
        }

    }

    override fun onFirstUserVisible() {
        if (userID == 0L) {
            return
        }
        userID?.let { initData(it, false) }
    }

    override fun onUserVisible() {
        userID?.let { initData(it, false) }

    }

    override fun onUserInvisible() {

    }

    override fun destroyViewAndThing() {
        EventUtil.getInstance().unregister(this)

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bundle = arguments
        if (bundle != null) {
            userID = bundle.getLong("userID")
        }
        EventUtil.getInstance().register(this)
    }

    companion object {
        val BUG_TAG = "fragmentMoment"
        val REQUEST_DATA = 0x1001
        val CHANGE_TAB = 0x1010
        val instance: FragmentMoment
            get() = FragmentMoment()

        fun newInstance(userID: Long?): FragmentMoment {
            val f = FragmentMoment()
            val args = Bundle()
            args.putLong("userID", userID!!)
            f.arguments = args
            return f

        }
    }
}
